package com.example.controller;

import com.example.pojo.Article;
import com.example.service.ArticleService;
import com.sun.org.apache.xpath.internal.operations.Bool;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;

@Controller
public class BlogController {

    @Autowired
    private ArticleService articleService;


    @RequestMapping("/index")
    public String indexPage(Model model, Integer page, Integer size, Boolean last) {
        page = (page == null) ? 0 : page;
        page = (page < 0) ? 0 : page;
        size = (size == null) ? 2 : size;
        last = (last == null) ? false : last;
        Page<Article> articles;
        if (last) {
            articles = articleService.selectPage(1, size);
            int totalPages = articles.getTotalPages();
            articles = articleService.selectPage(totalPages - 1, size);
        } else {

            articles = articleService.selectPage(page, size);
        }
        int pageNumber = articles.getPageable().getPageNumber();
        model.addAttribute("list", articles);
        model.addAttribute("pageNumber", pageNumber);
        model.addAttribute("size", size);

        return "index";
    }

    @RequestMapping("/default")
    public String defaultPage(Model model) {
        return "default";
    }


    @RequestMapping("/blog")
    @ResponseBody
    public Page<Article> blogPage(Integer page, Integer size, Boolean last) {
        page = (page == null) ? 0 : page;
        page = (page < 0) ? 0 : page;
        size = (size == null) ? 2 : size;
        last = (last == null) ? false : last;
        Page<Article> articles;
        if (last) {
            articles = articleService.selectPage(1, size);
            int totalPages = articles.getTotalPages();
            articles = articleService.selectPage(totalPages - 1, size);
        } else {
            articles = articleService.selectPage(page, size);
        }
        return articles;
    }


}
